package pkg

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

var (
	//自定义一个key
	keyInfo string
)

func init() {
	keyInfo = "WMHDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()"
}
func CreatedToken(id interface{}) (tokenString string)  {
	token := jwt.New(jwt.SigningMethodHS256)
	claims := make(jwt.MapClaims)
	//claims["exp"] = time.Now().Add(time.Hour * time.Duration(24 * 30)).Unix()
	claims["iat"] = time.Now().Unix()
	claims["uid"] = id
	token.Claims = claims
	tokenString, err := token.SignedString([]byte(keyInfo))
	if err != nil {
		fmt.Println(err)
		return
	} else {
		fmt.Println("myToken is: ",tokenString)
		return tokenString
	}
}

func CheckToken(tokenStr string) (interface{}, bool)  {
	////将token字符串转换为token对象（结构体
	tokenInfo , noToken := parseToken(tokenStr)
	if noToken != nil {
		fmt.Println("err=", noToken)
		return 0,false
	}
	//校验错误（基本）
	err := tokenInfo.Claims.Valid()
	if err!=nil{
		println(err.Error())
		return 0,false
	}
	finToken := tokenInfo.Claims.(jwt.MapClaims)
	//校验下token是否过期
	succ := finToken.VerifyExpiresAt(time.Now().Unix(),true)
	fmt.Println("succ",succ)
	//获取token中保存的用户信息
	fmt.Println(finToken)
	return finToken["uid"], true
}

func parseToken(s string) (*jwt.Token, error) {
	fn := func(token *jwt.Token) (interface{}, error) {
		return []byte(keyInfo), nil
	}
	return jwt.Parse(s, fn)
}